package controller;

import helpers.CrawlerOloHelper;
import helpers.SolrHelper;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import debug.RealEstateDebug;

import model.RealEstate;
import model.SearchParam;
import model.SearchResult;

/**
 * Servlet implementation class Crawler
 */
public class Crawler extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String alias = request.getParameter("alias");
		String url = "http://www.olo.vn/" + alias ;
		
		//Check exists
		SearchParam searchParam = new SearchParam();
		searchParam.setUrl(url);
		
		SearchResult sr = (SearchResult) SolrHelper.search(searchParam);
		ArrayList<RealEstate> realEstates = (ArrayList<RealEstate>) sr.getListRealEstate();
		if (realEstates.size() > 0 ) {			
			System.out.println("Have been exists this url: " + url);
			response.getWriter().println("Have been exists this url: " + url);
		} else {
			RealEstate re = CrawlerOloHelper.getContent(url);
			SolrHelper.add(re);
			RealEstateDebug.debug(re);
			response.setContentType("text/plain");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println("Get Content succuss: ");
			RealEstateDebug.debugWeb(re, response);
			System.out.println("Haven't been exists this url: " + url);
			response.getWriter().println("Haven't been exists this url: " + url);
		}
		
	}
}
